# 导入 Django 认证装饰器和渲染函数
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
# 导入 Django 通用视图类
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
# 导入作业提交和班级科目分配模型
from core.models.homework_submission import HomeworkSubmission
from core.models.class_subject_assignment import ClassSubjectAssignment
from ..models import Homework
from core.utils import log_operation

from django.forms import ModelForm
from django.forms.widgets import Select, Textarea, DateInput

# 通用Bootstrap表单基类
class BaseBootstrapForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 为所有字段添加form-control类
        for field in self.fields.values():
            if isinstance(field.widget, Select):
                field.widget.attrs.update({'class': 'form-select'})
            elif isinstance(field.widget, Textarea):
                field.widget.attrs.update({'class': 'form-control', 'rows': 5})
            elif isinstance(field.widget, DateInput):
                field.widget.attrs.update({'class': 'form-control', 'type': 'date'})
            else:
                field.widget.attrs.update({'class': 'form-control'})

# 自定义作业表单类（添加Bootstrap样式）
class HomeworkForm(BaseBootstrapForm):
    class Meta:
        model = Homework
        fields = ['class_subject', 'content', 'assigned_date', 'due_date']

# 获取单个作业详情的视图函数
from django.db.models import Count
from core.models.homework_submission import HomeworkSubmission


def homework_records_detail(request, homework_id):
    """
    根据作业 ID 获取单个作业的详情和提交记录，并渲染到页面。

    :param request: 请求对象
    :param homework_id: 作业 ID
    :return: 渲染后的作业详情页面
    """
    homework = Homework.objects.get(id=homework_id)
    submissions = HomeworkSubmission.objects.filter(homework=homework)
    # 获取模型中定义的所有状态选项
    status_choices = dict(HomeworkSubmission.STATUS_CHOICES)
    # 统计实际提交的状态数量
    status_counts = submissions.values('status').annotate(count=Count('status'))
    # 初始化包含所有状态的统计结果（数量为0）
    full_status_list = [{'status': status, 'count': 0} for status in status_choices.keys()]
    # 合并实际统计结果
    for count_data in status_counts:
        for item in full_status_list:
            if item['status'] == count_data['status']:
                item['count'] = count_data['count']
                break
    # 使用日志替代print调试
    # print('full_status_list',full_status_list)
    status_names=[]
    status_counts=[]
    for item in full_status_list:
        status_names.append(status_choices[item['status']])
        status_counts.append(item['count'])
    print('status_names',status_names)
    print('status_counts',status_counts)
    return render(request, 'homework/homework_records_detail.html', {'homework': homework, 'submissions': submissions, 
    'status_list': {'names':status_names,'counts':status_counts}})

# 作业列表视图类
from django.contrib.auth.mixins import LoginRequiredMixin
from core.models.role import Role

class HomeworkListView(LoginRequiredMixin, ListView):
    """
    显示作业列表的视图类。
    使用 Homework 模型，指定模板和上下文对象名称。
    """
    model = Homework
    template_name = 'homework/homework_list.html'
    context_object_name = 'homeworks'

    def get_queryset(self):
        user = self.request.user
        current_role = self.request.session.get('CURRENT_ROLE')
        
        if current_role == Role.HOMEROOM_TEACHER:
            # 班主任查看本班所有教师的作业
            return Homework.objects.filter(
                class_subject__class_id__homeroom_teacher=user
            ).select_related('class_subject', 'class_subject__class_id', 'class_subject__teacher')
        else:
            # 教师仅查看自己布置的作业
            return Homework.objects.filter(
                class_subject__teacher=user
            ).select_related('class_subject', 'class_subject__class_id')


# 作业创建视图类
class HomeworkCreateView(CreateView):
    def form_valid(self, form):
        response = super().form_valid(form)
        log_operation(
            user=self.request.user,
            operation_type='create',
            content_type='Homework',
            object_id=self.object.id,
            object_name=f'{self.object.class_subject}',
            request=self.request,
            details=f'布置作业: {self.object.content[:50]}'
        )
        return response
    """
    创建新作业的视图类。
    使用 Homework 模型，指定可编辑字段、模板和成功重定向 URL。
    """
    model = Homework
    form_class = HomeworkForm
    template_name = 'homework/homework_form.html'
    success_url = reverse_lazy('core:homework_list')


# 作业更新视图类
class HomeworkUpdateView(UpdateView):
    def form_valid(self, form):
        response = super().form_valid(form)
        log_operation(
            user=self.request.user,
            operation_type='update',
            content_type='Homework',
            object_id=self.object.id,
            object_name=f'{self.object.class_subject}',
            request=self.request,
            details=f'更新作业: {self.object.content[:50]}'
        )
        return response
    """
    template_name = 'homework/homework_form.html'
    更新现有作业的视图类（已集成Bootstrap表单样式）。
    使用自定义HomeworkForm，指定模板和成功重定向 URL。
    """
    model = Homework
    form_class = HomeworkForm
    template_name = 'homework/homework_form.html'
    success_url = reverse_lazy('core:homework_list')


# 作业删除视图类
class HomeworkDeleteView(DeleteView):
    def delete(self, request, *args, **kwargs):
        homework = self.get_object()
        log_operation(
            user=request.user,
            operation_type='delete',
            content_type='Homework',
            object_id=homework.id,
            object_name=f'{homework.class_subject}',
            request=request,
            details=f'删除作业: {homework.content[:50]}'
        )
        return super().delete(request, *args, **kwargs)
    """
    删除现有作业的视图类。
    使用 Homework 模型，指定模板和成功重定向 URL。
    """
    model = Homework
    template_name = 'homework/homework_confirm_delete.html'
    success_url = reverse_lazy('core:homework_list')


# 自定义作业提交表单类（添加Bootstrap样式）
class HomeworkSubmissionForm(BaseBootstrapForm):
    class Meta:
        model = HomeworkSubmission
        fields = ['homework', 'student', 'submission_time', 'status', 'feedback', 'reviewed_by', 'reviewed_at']
        widgets = {
            'submission_time': DateInput(attrs={'type': 'date', 'format': '%Y-%m-%d'}),
            'reviewed_at': DateInput(attrs={'type': 'date', 'format': '%Y-%m-%d'}),
        }

# 作业提交列表视图类
class HomeworkSubmissionListView(ListView):
    """
    显示作业提交列表的视图类。
    使用 HomeworkSubmission 模型，指定模板和上下文对象名称。
    """
    model = HomeworkSubmission
    template_name = 'homework/homework_submission_list.html'
    context_object_name = 'submissions'
    paginate_by = 10

    def get_queryset(self):
        return super().get_queryset().select_related('student', 'homework')

# 作业提交创建视图类
class HomeworkSubmissionCreateView(CreateView):
    """
    创建新作业提交的视图类。
    使用自定义 HomeworkSubmissionForm，指定模板和成功重定向 URL。
    """
    model = HomeworkSubmission
    form_class = HomeworkSubmissionForm
    template_name = 'homework/homework_submission_form.html'
    success_url = reverse_lazy('core:homework_submission_list')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['date_fields'] = ['submission_time', 'reviewed_at']
        return context

    def form_valid(self, form):
        import logging
        logger = logging.getLogger(__name__)
        logger.info('Received form data: %s', form.cleaned_data)
        # 检查是否已存在相同学生和作业的提交记录
        homework = form.cleaned_data['homework']
        student = form.cleaned_data['student']
        if HomeworkSubmission.objects.filter(homework=homework, student=student).exists():
            form.add_error(None, '该学生已提交过此作业，不能重复创建！')
            return self.form_invalid(form)
        response = super().form_valid(form)
        log_operation(
            user=self.request.user,
            operation_type='create',
            content_type='HomeworkSubmission',
            object_id=self.object.id,
            object_name=f'{self.object.student} - {self.object.homework}',
            request=self.request,
            details=f'提交作业: {self.object.status}'
        )
        return response

# 作业提交更新视图类
class HomeworkSubmissionUpdateView(UpdateView):
    def form_valid(self, form):
        response = super().form_valid(form)
        log_operation(
            user=self.request.user,
            operation_type='update',
            content_type='HomeworkSubmission',
            object_id=self.object.id,
            object_name=f'{self.object.student} - {self.object.homework}',
            request=self.request,
            details=f'更新作业提交状态: {self.object.status}'
        )
        return response
    """
    更新现有作业提交的视图类。
    使用自定义 HomeworkSubmissionForm，指定模板和成功重定向 URL。
    """
    model = HomeworkSubmission
    form_class = HomeworkSubmissionForm
    template_name = 'homework/homework_submission_form.html'
    success_url = reverse_lazy('core:homework_submission_list')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['date_fields'] = ['submission_time', 'reviewed_at']
        return context

    def form_valid(self, form):
        import logging
        logger = logging.getLogger(__name__)
        logger.info('Received form data: %s', form.cleaned_data)
        return super().form_valid(form)

# 作业提交删除视图类
class HomeworkSubmissionDeleteView(DeleteView):
    """
    删除现有作业提交的视图类。
    使用 HomeworkSubmission 模型，指定模板和成功重定向 URL。
    """
    model = HomeworkSubmission
    template_name = 'homework/homework_submission_confirm_delete.html'
    success_url = reverse_lazy('core:homework_submission_list')

    def get_success_url(self):
        import logging
        logger = logging.getLogger(__name__)
        logger.info('Deleted homework submission with ID: %s', self.object.pk)
        return super().get_success_url()
from core.models.classinfo import ClassInfo
from core.models.student import Student
from django.db.models import Q
import logging
logger = logging.getLogger(__name__)

@login_required
# 统计指定班级和日期的作业情况
def class_homework_stats(request, classid, date_str):
    print("classid",classid)
    print("date_str",date_str)
    try:
        from datetime import datetime
        target_date = datetime.strptime(date_str, '%Y-%m-%d').date()
        class_info = ClassInfo.objects.get(id=classid)
        logger.info(f'获取到班级信息: {class_info}')

        # 通过班级获取班级学科分配
        class_subject_assignments = ClassSubjectAssignment.objects.filter(class_id=class_info)
        logger.info(f'获取到 {class_subject_assignments.count()} 条班级学科分配记录')
        logger.info(f'班级学科分配详情: {[str(assignment) for assignment in class_subject_assignments]}')

        # 初始化作业统计数据
        homework_stats = {}
        subject_without_homework = []

        # 获取所有该班级的学生
        students = Student.objects.filter(classes=class_info)
        logger.info(f'获取到 {students.count()} 名该班级的学生')

        for assignment in class_subject_assignments:
            logger.info(f'正在处理学科分配: {assignment}')
            # 通过学科和截止时间确定作业
            homeworks = Homework.objects.filter(
                class_subject=assignment,
                due_date=target_date
            )
            logger.info(f'学科 {assignment.subject} 在 {target_date} 有 {homeworks.count()} 条作业记录')
            logger.info(f'作业详情: {[str(homework) for homework in homeworks]}')

            if not homeworks.exists():
                subject_without_homework.append(assignment.subject)
                continue

            for homework in homeworks:
                # 通过学生和作业查作业提交记录
                submissions = HomeworkSubmission.objects.filter(homework=homework)
                logger.info(f'作业 {homework} 有 {submissions.count()} 条提交记录')
                logger.info(f'提交记录详情: {[str(submission) for submission in submissions]}')
                student_status = {}

                # 初始化所有学生状态为未提交
                for student in students:
                    student_status[student] = { 
                        'status': 'missing',
                        'submitted': False
                    }

                # 更新已提交学生的状态
                for submission in submissions:
                    student_status[submission.student] = { 
                        'status': submission.status,
                        'submitted': True
                    }

                homework_stats[assignment.subject] = { 
                    'homework': homework,
                    'students': student_status
                }

        logger.info(f'作业统计数据: {homework_stats}')
        logger.info(f'无作业的学科: {subject_without_homework}')
        return render(request, 'homework/class_homework_stats.html', {
            'class_info': class_info,
            'date': target_date,
            'homework_stats': homework_stats,
            'subject_without_homework': subject_without_homework
        })
    except Exception as e:
        logger.error('Error in class_homework_stats: %s', str(e))
        return render(request, 'error.html', {'error': '获取作业统计信息时出错，请稍后重试。'})
    except ClassInfo.DoesNotExist:
        return render(request, 'error.html', {'message': '未找到该班级信息'})
    except ValueError:
        return render(request, 'error.html', {'message': '日期格式不正确，请使用 YYYY-MM-DD 格式'})